<template>
  <view class="comment-section">
    <!-- 评论输入框 -->
    <view class="comment-input-section">
      <view class="input-container">
        <textarea
          v-model="commentText"
          placeholder="写下你的评论..."
          class="comment-input"
          :maxlength="500"
          auto-height
        />
        <view class="input-actions">
          <text class="char-count">{{ commentText.length }}/500</text>
          <button
            class="submit-btn"
            :disabled="!commentText.trim() || isSubmitting"
            @click="submitComment"
          >
            {{ isSubmitting ? '发送中...' : '发送' }}
          </button>
        </view>
      </view>
    </view>

    <!-- 评论列表 -->
    <view class="comment-list">
      <view class="comment-header">
        <text class="comment-title">评论 ({{ totalComments }})</text>
      </view>

      <view class="comment-items">
        <view
          class="comment-item"
          v-for="comment in comments"
          :key="comment.id"
        >
          <view class="comment-avatar">
            <image
              v-if="comment.user.avatarUrl"
              :src="comment.user.avatarUrl"
              class="avatar-image"
            />
            <view v-else class="default-avatar">
              <text class="avatar-text">{{ comment.user.nickname?.charAt(0) || '用' }}</text>
            </view>
          </view>
          <view class="comment-content">
            <view class="comment-header-info">
              <text class="comment-author">{{ comment.user.nickname }}</text>
              <text class="comment-time">{{ formatRelativeTime(comment.createTime) }}</text>
            </view>
            <text class="comment-text">{{ comment.content }}</text>
            <view class="comment-actions">
              <view
                class="action-item"
                :class="{ active: comment.isLiked }"
                @click="toggleCommentLike(comment)"
              >
                <uni-icons
                  :type="comment.isLiked ? 'heart-filled' : 'heart'"
                  size="14"
                  :color="comment.isLiked ? '#ff4757' : '#999'"
                />
                <text class="action-text">{{ formatNumber(comment.likeCount) }}</text>
              </view>
            </view>
          </view>
        </view>

        <!-- 加载更多 -->
        <view class="load-more" v-if="hasMore">
          <uni-load-more
            :status="loadStatus"
            @clickLoadMore="loadMoreComments"
          />
        </view>

        <!-- 空状态 -->
        <view class="empty-comments" v-if="comments.length === 0 && !isLoading">
          <uni-icons type="chat" size="48" color="#ddd"></uni-icons>
          <text class="empty-text">暂无评论，快来抢沙发吧~</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { newsApi } from '@/api/index.js'
import { formatRelativeTime, formatNumber } from '@/utils/format.js'

// 定义 props
const props = defineProps({
  newsId: {
    type: Number,
    required: true
  }
})

// 响应式数据
const commentText = ref('')
const comments = ref([])
const totalComments = ref(0)
const isSubmitting = ref(false)
const isLoading = ref(false)
const hasMore = ref(true)
const loadStatus = ref('more')
const currentPage = ref(0)

// 页面加载时获取评论
onMounted(() => {
  loadComments()
})

// 加载评论列表
const loadComments = async (isLoadMore = false) => {
  if (isLoading.value) return

  try {
    isLoading.value = true
    loadStatus.value = 'loading'

    const page = isLoadMore ? currentPage.value + 1 : 0
    const response = await newsApi.getNewsComments(props.newsId, {
      page,
      size: 20
    })

    if (response.code === 200) {
      const newComments = response.data.content || []

      if (isLoadMore) {
        comments.value.push(...newComments)
        currentPage.value = page
      } else {
        comments.value = newComments
        currentPage.value = 0
      }

      totalComments.value = response.data.totalElements || 0
      hasMore.value = !response.data.last
      loadStatus.value = hasMore.value ? 'more' : 'noMore'
    }
  } catch (error) {
    console.error('加载评论失败:', error)
    uni.showToast({
      title: '加载评论失败',
      icon: 'none'
    })
    loadStatus.value = 'more'
  } finally {
    isLoading.value = false
  }
}

// 加载更多评论
const loadMoreComments = () => {
  loadComments(true)
}

// 提交评论
const submitComment = async () => {
  if (!commentText.value.trim() || isSubmitting.value) return

  try {
    isSubmitting.value = true

    const response = await newsApi.postComment(props.newsId, commentText.value.trim())

    if (response.code === 200) {
      uni.showToast({
        title: '评论成功',
        icon: 'success'
      })

      commentText.value = ''
      // 重新加载评论列表
      loadComments()
    }
  } catch (error) {
    console.error('发表评论失败:', error)
    uni.showToast({
      title: '发表评论失败',
      icon: 'none'
    })
  } finally {
    isSubmitting.value = false
  }
}

// 切换评论点赞状态
const toggleCommentLike = async (comment) => {
  try {
    const response = await newsApi.likeComment(comment.id)

    if (response.code === 200) {
      comment.isLiked = !comment.isLiked
      comment.likeCount += comment.isLiked ? 1 : -1
    }
  } catch (error) {
    console.error('点赞失败:', error)
    uni.showToast({
      title: '操作失败',
      icon: 'none'
    })
  }
}
</script>

<style scoped>
.comment-section {
  background: #f8f9fa;
  padding: 30rpx;
}

.comment-input-section {
  background: #ffffff;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 30rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.08);
}

.input-container {
  display: flex;
  flex-direction: column;
  gap: 20rpx;
}

.comment-input {
  min-height: 120rpx;
  padding: 20rpx;
  border: 2rpx solid #e9ecef;
  border-radius: 12rpx;
  font-size: 28rpx;
  line-height: 1.5;
  resize: none;
}

.comment-input:focus {
  border-color: #4CAF50;
  outline: none;
}

.input-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.char-count {
  font-size: 24rpx;
  color: #999999;
}

.submit-btn {
  background: #4CAF50;
  color: #ffffff;
  border: none;
  border-radius: 20rpx;
  padding: 16rpx 32rpx;
  font-size: 26rpx;
  font-weight: 500;
}

.submit-btn:disabled {
  background: #cccccc;
  color: #999999;
}

.comment-list {
  background: #ffffff;
  border-radius: 16rpx;
  overflow: hidden;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.08);
}

.comment-header {
  padding: 30rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.comment-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #333333;
}

.comment-items {
  padding: 0 30rpx;
}

.comment-item {
  display: flex;
  gap: 20rpx;
  padding: 30rpx 0;
  border-bottom: 1rpx solid #f0f0f0;
}

.comment-item:last-child {
  border-bottom: none;
}

.comment-avatar {
  width: 80rpx;
  height: 80rpx;
  border-radius: 50%;
  overflow: hidden;
  flex-shrink: 0;
}

.avatar-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.default-avatar {
  width: 100%;
  height: 100%;
  background: linear-gradient(135deg, #4CAF50, #66BB6A);
  display: flex;
  align-items: center;
  justify-content: center;
}

.avatar-text {
  color: #ffffff;
  font-size: 32rpx;
  font-weight: 600;
}

.comment-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 12rpx;
}

.comment-header-info {
  display: flex;
  align-items: center;
  gap: 20rpx;
}

.comment-author {
  font-size: 26rpx;
  font-weight: 500;
  color: #333333;
}

.comment-time {
  font-size: 24rpx;
  color: #999999;
}

.comment-text {
  font-size: 28rpx;
  color: #333333;
  line-height: 1.6;
}

.comment-actions {
  display: flex;
  gap: 40rpx;
  margin-top: 16rpx;
}

.action-item {
  display: flex;
  align-items: center;
  gap: 8rpx;
  padding: 8rpx 16rpx;
  border-radius: 20rpx;
  transition: all 0.3s ease;
}

.action-item.active {
  background: rgba(255, 71, 87, 0.1);
}

.action-text {
  font-size: 24rpx;
  color: #999999;
}

.action-item.active .action-text {
  color: #ff4757;
}

.load-more {
  padding: 30rpx 0;
}

.empty-comments {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 20rpx;
  padding: 80rpx 0;
}

.empty-text {
  font-size: 28rpx;
  color: #999999;
}
</style>
